package kr.hkit.powerjava.chapter25.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class QuizServer {
	public static void main(String[] args) throws IOException {
		// 에러구분위해 try catch 각각 둠,.
		ServerSocket serverSocket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		
		try {
			serverSocket = new ServerSocket(5555);
		} catch (IOException e) {
			System.err.println("다음의 포트 번호에 연결할 수 없습니다.: 5555");
			System.exit(-1);	//비정상종료
		}
		
		Socket clientSocket = null;
		
		try {
			clientSocket = serverSocket.accept();
		} catch (IOException e) {
			System.err.println("accept() 실패");
			System.exit(-1);	//비정상종료
		} 

		out = new PrintWriter(clientSocket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(
								clientSocket.getInputStream()));
		
		String inputLine, outputLine;
		QuizProtocol qp = new QuizProtocol();
		
		outputLine = qp.process(null);	//메세지가 들어옴
		out.println(outputLine);	//클라이언트에게 문제 시작됨을 전송하는 것
									//퀴즈를 시작합니다!!
		
		while((inputLine = in.readLine()) != null) {	//클라이언트로 부터 받음
														//y/n을 받음
			outputLine = qp.process(inputLine);			//답이 맞는지 확인 후 문제 확인
			out.println(outputLine);					//문제를 보내줌
			if(outputLine.equalsIgnoreCase("quit"))
				break;
		}
		
		out.close();
		in.close();
		clientSocket.close();
		serverSocket.close();
	}
}